package
{
	import flash.geom.Point;

	/**
	 *s手势对象 
	 * @author hc
	 * 
	 */	
	public class Instance
	{
		private static const SEQUENCE_SAMPLE_SIZE:int = 16;
		
		
		private static const ORIENTATIONS:Array = [
			0, (Math.PI / 4), (Math.PI / 2), (Math.PI * 3 / 4),
			Math.PI, -0, (-Math.PI / 4), (-Math.PI / 2),
				(-Math.PI * 3 / 4), -Math.PI
			];
		
		public var id:Number;
		public var vector:Vector.<Number>;
		public var label:String;
		public var score:Number;
		
		public function Instance(id:Number, sample:Vector.<Number>, sampleName:String) {
			this.id = id;
			vector = sample;
			label = sampleName;
		}
		
		private function normalize():void{
			var _scaled:Vector.<Point> = new Vector.<Point>();
			for(var i:int = 0 ;i < vector.length; i +=2){
				_scaled.push(new Point(vector[i],vector[i+1]));
			}
			
			_scaled.sort(sortOnX);
			// get leftmost point
			var _left:Point = new Point(_scaled[0].x, _scaled[0].y);
			// get rightmost point
			var _right:Point = new Point(_scaled[_scaled.length-1].x, _scaled[_scaled.length-1].y);
			
			_scaled.sort(sortOnY);
			// get topmost point
			var _top:Point = new Point(_scaled[0].x, _scaled[0].y);
			// get bottom-most point
			var _bottom:Point = new Point(_scaled[_scaled.length-1].x, _scaled[_scaled.length-1].y);
			
			var _width:Number = _right.x - _left.x;
			var _height:Number = _bottom.y - _top.y;
			
			var _ratio:Number;
			if (_width > _height) {
				// get scale ratio based on width
				_ratio = 1/_width;
			} else {
				// get scale ratio based on height
				_ratio = 1/_height;
			}
			
			for (i=0; i<vector.length; i+=2) {
				vector[i] -= _left.x;
				vector[i+1] -= _top.y;
				vector[i] *= _ratio;
				vector[i+1] *= _ratio;
			}
		}
		
		private function sortOnX(a:Point, b:Point):Number {
			if (a.x < b.x) {
				return -1;
			} else if (a.x > b.x) {
				return 1;
			} else {
				return 0;
			}
		}
		
		private function sortOnY(a:Point, b:Point):Number {
			if (a.y < b.y) {
				return -1;
			} else if (a.y > b.y) {
				return 1;
			} else {
				return 0;
			}
		}
		
		/**
		 *创建一个手势对象 
		 * @param posList
		 * @param label
		 * @return 
		 * 
		 */		
		public static function createInstance(posList:Vector.<Number>,label:String = null):Instance {
			var pts:Vector.<Number> = GestureUtils.temporalSampling(posList,SEQUENCE_SAMPLE_SIZE);
			var instance:Instance = new Instance(Math.random(), pts, label);
			instance.normalize();
			return instance;
		}
	}
}